﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientsRouteHistory.aspx.cs" Inherits="GPSTrackingWebsiteManager.Pages.ClientsRouteHistory" %>

<!DOCTYPE html>

<link href="../../Css/GPSTrackingWebsite.css" rel="stylesheet" />
<link href="../../Css/messi.css" rel="stylesheet" />
<script src="../../Javascript/jquery-1.11.1.min.js"></script>
<script src="../../Javascript/messi.js"></script>
<script src="../../Javascript/Custom.js"></script>
<script src="../../Javascript/WindowMessageManager.js"></script>
<script src="../../Javascript/ObjectsV2.js"></script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
        <script type="text/javascript">

            //Windows Message Manager 
            var objWindowsMessageManager = new WindowsMessageManager();
            objWindowsMessageManager.run();

            var opener = GetRadWindow();
            var Routes = new Routes();
            var Companies = new Companies();
            var ClientsProcess = new ClientsProcess();
            //var BusStopsManager = new BusStopsManager();

            var firstRouteHasGPSPoints = true;

            function GetRadWindow() {
                var oWindow = null;
                if (window.radWindow)
                    oWindow = window.radWindow;
                else if (window.frameElement.radWindow)
                    oWindow = window.frameElement.radWindow;
                return oWindow.BrowserWindow;
            }

            function initializeObjects() {
                opener.objMapControl.initializeClientsHistoryObject();
            }

            function clearObjects() {
                ClientsProcess.hideObjects(opener.globalClientsRouteHistory, opener.objMapControl, opener.globalClientsRouteHistory.clientsToVisitList);
                getBtnPlayPause().set_selectedToggleStateIndex(1);
                getBtnPlayPause().set_checked(false);
                stopSlideMovement();
            }

            function restorePage(){
                ClientsProcess.showObjects(opener.globalClientsRouteHistory, opener.objMapControl, opener.globalClientsRouteHistory.clientsToVisitList);
            }

            function getCompaniesByAdminUsername() {
                initializeObjects();
                requestStart(getrpvRoutesUpdateControl());
                PageMethods.wsGetCompaniesByAdminUsername(getCompaniesByAdminUsernameOk, getCompaniesByAdminUsernameError);
            }

            //Utilizada
            function getrpvPlayerUpdateControl() {
                return "<%=  rpvPlayer.ClientID %>";
        }

        //Utilizada
        function getrpvRoutesUpdateControl() {
            return "<%=  rpvRoutes.ClientID %>";
        }

        //Utilizada
        function getCompaniesByAdminUsernameOk(object) {
            Companies.openXMLCompaniesByAdminUsername(object, opener.globalClientsRouteHistory.companiesList);
            Companies.loadCompaniesDataSource(getCompaniesGrid(), opener.globalClientsRouteHistory.companiesList, opener.globalClientsRouteHistory.companiesDataSource);
            if (opener.globalClientsRouteHistory.companiesList.length == 1) {
                getCompaniesGrid().selectItem(0);
                opener.globalClientsRouteHistory.companyIDSelected = opener.globalClientsRouteHistory.companiesList[0].companyID;
                responseEnd(getrpvRoutesUpdateControl());
            }
            else {
                responseEnd(getrpvRoutesUpdateControl());
            }
        }

        //Utilizada
        function getCompaniesByAdminUsernameError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
        }

        //Utilizada
        function getCompaniesGrid() {
            try {
                return $find("<%= rgCompaniesGrid.ClientID %>").get_masterTableView();
            }
            catch (ex) {
                setTimeout(getCompaniesGrid, 100);
            }
        }

        //Utilizada
        function getClientsProcessGrid() {
            try {
                return $find("<%= ClientsProcessGrid.ClientID %>").get_masterTableView();
            }
            catch (ex) {
                setTimeout(getClientsProcessGrid, 100);
            }
        }


        //Utilizada
        function CompaniesGrid_OnRowClick(sender, args) {
            ClientsProcess.clearClientsToVisit(opener);
            opener.globalClientsRouteHistory.companyIDSelected = args.getDataKeyValue("CompanyID");
            if (opener.globalClientsRouteHistory.dateSelected != null && opener.globalClientsRouteHistory.companyIDSelected != null) {
                requestStart(getrpvRoutesUpdateControl());
                PageMethods.wsGetClientsProcessByDateByCompanyID(opener.globalClientsRouteHistory.dateSelected, opener.globalClientsRouteHistory.companyIDSelected, getClientsProcessByDateByCompanyIDOk, getClientsProcessByDateByCompanyIDError);
            }
        }

        //Utilizada
        function ClientsProcessGrid_OnRowClick(sender, args) {
            ClientsProcess.clearClientsToVisit(opener);
            opener.globalClientsRouteHistory.usernameSelected = args.getDataKeyValue("Username");
            opener.globalClientsRouteHistory.gpsImeiSelected = args.getDataKeyValue("GPSImei");
            opener.globalClientsRouteHistory.positionOrigin = opener.objMapControl.addPosition(stringToFloatForPosition(args.getDataKeyValue("LatOrigin")), stringToFloatForPosition(args.getDataKeyValue("LngOrigin")));
            if(isDate(args.getDataKeyValue("Date"))){
                opener.globalClientsRouteHistory.dateSelected = getFormatDate(args.getDataKeyValue("Date"));
            }
            
            getClientsToVisitByUsernameByGPSImeiByDate();
        }

        //Utilizada
        function getClientsToVisitByUsernameByGPSImeiByDate() {
            if (opener.globalClientsRouteHistory.companyIDSelected != null && opener.globalClientsRouteHistory.gpsImeiSelected != null) {
                requestStart(getrpvRoutesUpdateControl());
                PageMethods.wsGetClientsToVisitByUsernameByGPSImeiByDate(opener.globalClientsRouteHistory.companyIDSelected, opener.globalClientsRouteHistory.usernameSelected, opener.globalClientsRouteHistory.gpsImeiSelected, opener.globalClientsRouteHistory.dateSelected, getClientsToVisitByUsernameByGPSImeiByDateOk, getClientsToVisitByUsernameByGPSImeiByDateError);
            }
        }

        //Utilizada
        function getClientsToVisitByUsernameByGPSImeiByDateOk(object) {
            ClientsProcess.openXMLClientsByCompanyIDAndUsernameAndGPSImeiAndDate(opener.objMapControl, object, opener.globalClientsRouteHistory.clientsToVisitList);

            //globalObject.temporalyList.push(objMapControl.addPosition(stringToFloatForPosition(latitude), stringToFloatForPosition(longitude)));
            
            opener.globalClientsRouteHistory.temporalyIndex = 0;
            opener.globalClientsRouteHistory.temporalyInterval = setInterval(function () { loadClientsRouteDisplay(opener); }, opener.globalClientsRouteHistory.timeToCalculateRoute);


            for (i = 0; i < opener.globalClientsRouteHistory.clientsToVisitList.length; i++) {

                /*opener.globalClientsRouteHistory.busStopsList[i].checked = true;*/
                if (getckbCenterClients().checked) {
                    opener.objMapControl.centerMap(opener.objMapControl.getPositionMarker(opener.globalClientsRouteHistory.globalClientsRouteHistory[i].marker));
                }

                if (getckbZoomClients().checked) {
                    opener.objMapControl.zoomMap(16);
                }
                
                
            }
            //alert(opener.globalClientsRouteHistory.clientsToVisitList.length);
            
            //BusStopsManager.showAllBusStopsChecked(opener.globalClientsRouteHistory.busStopsList);

            loadRouteHistory();
            responseEnd(getrpvRoutesUpdateControl());
        }

        //Utilizada
        function getClientsToVisitByUsernameByGPSImeiByDateError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            objWindowsMessageManager.show_Error(error.get_message(), titles.busStopsTitle);
        }

        //Utilizada
        function loadClientsRouteDisplay(opener) {
            if (opener.globalClientsRouteHistory.temporalyIndex <= opener.globalClientsRouteHistory.clientsToVisitList.length) {
                if (opener.globalClientsRouteHistory.temporalyIndex == 0) {
                    opener.globalClientsRouteHistory.temporalyIndex++;
                    opener.objMapControl.addClientsRouteHistoryClickDB(opener.globalClientsRouteHistory.positionOrigin);
                }
                else {
                    opener.objMapControl.addClientsRouteHistoryClickDB(opener.globalClientsRouteHistory.clientsToVisitList[(opener.globalClientsRouteHistory.temporalyIndex++) - 1].position);
                }
            }
            else {
                clearInterval(opener.globalClientsRouteHistory.temporalyInterval);
                responseEnd(getrpvRoutesUpdateControl());
            }
        }

        //Utilizada
        function GetAllBusRouteDetailsByBusRouteIDError(error) {
            responseEnd(getrpvBusStopsManagerUpdateControl());
            objWindowsMessageManager.show_Error(error.get_message(), titles.busStopsTitle);
        }




        //Utilizada
        function getClientsProcessByDateByCompanyID(sender, eventArgs) {
            if (sender != null) {
                if (eventArgs.get_renderDay().get_isSelected()) {
                    ClientsProcess.clearClientsToVisit(opener);
                    opener.globalClientsRouteHistory.dateSelected = sender.DateTimeFormatInfo.FormatDate(eventArgs.get_renderDay().get_date(), "yyyy/MM/dd");
                    //var dfi = sender.DateTimeFormatInfo;
                    //var formattedDate = dfi.FormatDate(date, dfi.ShortDatePattern);
                    //alert(formattedDate + " was just " +
                    //(eventArgs.get_renderDay().get_isSelected() ? "selected. " : "unselected. "));
                    if (opener.globalClientsRouteHistory.dateSelected != null && opener.globalClientsRouteHistory.companyIDSelected != null && opener.globalClientsRouteHistory.companyIDSelected != -1) {
                        requestStart(getrpvRoutesUpdateControl());
                        PageMethods.wsGetClientsProcessByDateByCompanyID(opener.globalClientsRouteHistory.dateSelected, opener.globalClientsRouteHistory.companyIDSelected, getClientsProcessByDateByCompanyIDOk, getClientsProcessByDateByCompanyIDError);
                    }
                }
            }
        }

        //Utilizada
        function getClientsProcessByDateByCompanyIDOk(object) {
            ClientsProcess.openXMLClientsProcess(object, opener.globalClientsRouteHistory.clientsProcessList);
            ClientsProcess.loadClientsProcessDataSource(getClientsProcessGrid(), opener.globalClientsRouteHistory.clientsProcessList, opener.globalClientsRouteHistory.clientsProcessDataSource);


            responseEnd(getrpvRoutesUpdateControl());
        }

        //Utilizada
        function getClientsProcessByDateByCompanyIDError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
        }

        function loadRouteHistory() {
            //if (Routes.isValidToLoadRoute(opener.globalGPSImei.imeiSelected, getDateSelected().get_textBox().value)) {
            //    requestStart(getrpvRoutesUpdateControl());
            //    Routes.enableDisableSliderRoute(false, getSliderRouter());
            //getBtnLoadRoute().disabled = true;
            getBtnPlayPause().set_enabled(false);
            //FirstSelection
            firstRouteHasGPSPoints = true;

            //oWndShow.BusStopsRouteHistory.window.width = "100px";


            PageMethods.wsLoadClientsRouteHistory(opener.globalClientsRouteHistory.companyIDSelected, opener.globalClientsRouteHistory.usernameSelected, opener.globalClientsRouteHistory.gpsImeiSelected, opener.globalClientsRouteHistory.dateSelected, true, loadRouteHistoryFirstSelectionOk, loadRouteHistoryFirstSelectionError);
            //}
        }

        function loadRouteHistoryFirstSelectionOk(stringCollection) {
            if (stringCollection == "") {
                firstRouteHasGPSPoints = false;
            }
            else {
                opener.objMapControl.setPositionMarker(opener.globalClientsRouteHistory.GPSImeiRoute, null);
                ClientsProcess.openCollectionStringProcessDetailsFirsSelection(stringCollection, opener, opener.globalClientsRouteHistory);
                //alert(opener.globalClientsRouteHistory.trackDataByImei.length);
                getBtnPlayPause().set_enabled(true);

                //SecondSelection
                //PageMethods.wsLoadRouteHistory(opener.globalGPSImei.imeiSelected, getFormatDate(getDateSelected().get_textBox().value), false, loadRouteHistorySecondSelectionOk, loadRouteHistorySecondSelectionError);

                clearInterval(opener.globalClientsRouteHistory.refreshIntervalId);
                getBtnPlayPause().set_enabled(true);
                slider = getSliderRouter();
                slider.set_maximumValue(opener.globalClientsRouteHistory.trackDataByImei.length - 1);

                opener.globalClientsRouteHistory.currentSlideRouteNumber = 0;
                opener.objMapControl.setIconMarker(opener.globalClientsRouteHistory.GPSImeiRoute, opener.globalClientsRouteHistory.trackDataByImei[0].image);

                slider.set_value(0);

                //opener.globalRoutes.firstRoute = true;
                //opener.objMapControl.routes = [];
                //drawDrivingRoute(opener);

                //getResumenRouteHistory();
            }
            //Routes.enableDisableSliderRoute(true, getSliderRouter());

        }

        /*function getResumenRouteHistory() {
            PageMethods.wsGetResumenRouteHistory(opener.globalClientsRouteHistory.numControlSelected, getResumenRouteHistoryOk, getResumenRouteHistoryError);
        }

        function getResumenRouteHistoryOk(resumen) {
            ClientsProcess.openXMLResumenProcessDetails(resumen, opener);
            updateCurrentPositionRouteHistory(opener.globalClientsRouteHistory.currentSlideRouteNumber);
            responseEnd(getrpvRoutesUpdateControl());
        }

        function getResumenRouteHistoryError(error) {
            responseEnd(getrpvBusStopsManagerUpdateControl());
            objWindowsMessageManager.show_Error(error.get_message(), titles.busStopsTitle);
        }*/

        function loadRouteHistorySecondSelectionOk(stringCollection) {
            if (stringCollection == "") {
                if (!firstRouteHasGPSPoints) {
                    objWindowsMessageManager.show_Info("No hay rutas definidas para la fecha seleccionada.", titles.RoutesHistoryTitle);
                    getBtnLoadRoute().value = "Cargar Ruta";
                    getBtnLoadRoute().disabled = false;
                    responseEnd(getrpvRoutesUpdateControl());
                }
            }
            else {
                Routes.openCollectionStringTrackDataByImeiSecondSelection(stringCollection, opener);
            }

            getBtnLoadRoute().value = "Cargando... 1%";
            opener.globalRoutes.firstRoute = true;
            opener.objMapControl.routes = [];
            drawDrivingRoute(opener);
        }

        function loadRouteHistoryFirstSelectionError(error) {
            objWindowsMessageManager.show_Error(error.get_message());
            responseEnd(getrpvRoutesUpdateControl());
        }

        function loadRouteHistorySecondSelectionError(error) {
            objWindowsMessageManager.show_Error(error.get_message());
            responseEnd(getrpvRoutesUpdateControl());
        }

        function drawDrivingRoute(opener) {
            opener.globalRoutes.currentGpsPoint = 0;
            opener.globalRoutes.firstRoute = true;
            opener.objMapControl.clearStopsMarkers();
            opener.objMapControl.clearPeopleCounterMarkers();
            opener.globalRoutes.peopleTotalIn = -1;
            opener.globalRoutes.peopleTotalOut = -1;
            //Routes.showHistoryRoute(opener);
            //opener.objMapControl.showDirectionDisplay(opener.globalClientsRouteHistory.directionDisplay);
            opener.objMapControl.showClientsDirectionDisplay(opener.globalClientsRouteHistory);
            opener.globalRoutes.doesnWorkDrawRoute = false;
            opener.globalRoutes.lastOne = false;
            opener.globalRoutes.mtsRoute = opener.globalRoutes.mtsRouteStar;
            opener.globalRoutes.refreshIntervalId = setInterval(drawDrivingRouteTimer, 100);
            responseEnd(getrpvRoutesUpdateControl());
        }

        function drawDrivingRouteTimer() {

            if (opener.globalClientsRouteHistory.trackDataByImei.length > 1) {
                var lstart = 0;

                var existsMarker = false;
                var stopTimes = 0;
                var initialStop = 0;

                for (opener.globalRoutes.currentGpsPoint = opener.globalRoutes.currentGpsPoint; opener.globalRoutes.currentGpsPoint < opener.globalClientsRouteHistory.trackDataByImei.length - 2; opener.globalRoutes.currentGpsPoint++) {
                    getBtnLoadRoute().value = "Cargando..." + formatTwoDecimals((opener.globalRoutes.currentGpsPoint / opener.globalClientsRouteHistory.trackDataByImei.length) * 100) + "%";


                    /*if (opener.globalRoutes.peopleTotalIn == -1 && opener.globalRoutes.peopleTotalOut == -1) {
                        opener.globalRoutes.peopleTotalIn = opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn;
                        opener.globalRoutes.peopleTotalOut = opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut;
                    }*/

                    if (opener.globalRoutes.peopleTotalIn != opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn || opener.globalRoutes.peopleTotalOut != opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut) {// && (opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn == opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].peopleTotalIn))){// || (opener.globalRoutes.peopleTotalOut != opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut && opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut == opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].peopleTotalOut)) {
                        var myPeopleCounterMarker = new PeopleCounterMarker();

                        myPeopleCounterMarker.setPeopleCounterMarker(opener.objMapControl.addPeopleCounterMarker(images.locationPeopleCounter, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, ""), opener.objMapControl.addInfoWindow(), opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleIn, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleOut, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalInside, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut);

                        //if (!getCkbSiNoShowStops().checked) {
                        //    myStopMarker.stopMarker.setVisible(false);
                        //}

                        opener.globalList.peopleCounterMarkers.push(myPeopleCounterMarker);

                        opener.globalRoutes.peopleTotalIn = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn;
                        opener.globalRoutes.peopleTotalOut = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut;
                    }









                    if (lstart == 0) {
                        if (opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm >= opener.globalRoutes.mtsRoute) {
                            if (opener.globalRoutes.doesnWorkDrawRoute) {
                                opener.globalRoutes.doesnWorkDrawRoute = false;
                                lstart = 0;
                                opener.globalRoutes.destination = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position;
                                opener.objMapControl.getDrivingRoute();
                                return;
                            }
                            else {
                                lstart = 1;
                                opener.globalRoutes.origin = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position;
                                if (opener.globalList.stopsMarkers.length > 0 && opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                                    opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                }
                            }
                        }
                        else {
                            if (opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm < opener.globalRoutes.mtsStop) {
                                if (!existsMarker) {
                                    if (initialStop == 0) {
                                        initialStop = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                    }
                                    if (stopTimes > opener.globalRoutes.timesStop) {

                                        var myStopMarker = new StopMarker();

                                        myStopMarker.setStopMarker(opener.objMapControl.addStopMarker(images.locationStop, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, ""), opener.objMapControl.addInfoWindow(), initialStop);

                                        if (!getCkbSiNoShowStops().checked) {
                                            myStopMarker.stopMarker.setVisible(false);
                                        }

                                        opener.globalList.stopsMarkers.push(myStopMarker);

                                        existsMarker = true;
                                    }
                                    else {
                                        stopTimes++;
                                    }
                                }
                                else {
                                    if (opener.globalList.stopsMarkers.length > 0) {
                                        opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                    }
                                }
                            }
                        }
                    } else {
                        if ((opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm < opener.globalRoutes.mtsRoute) || (Routes.changeDirectionPosition(opener, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position))) {
                            lstart = 0;
                            opener.globalRoutes.destination = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position;

                            opener.objMapControl.getDrivingRoute();
                            return;
                        }
                    }
                }
                if (lstart = 1) {
                    opener.globalRoutes.destination = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position;
                    opener.globalRoutes.lastOne = true;

                    if (opener.globalList.stopsMarkers.length > 0 && opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                        opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalClientsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                    }

                    setTimeout(opener.objMapControl.getDrivingRoute, 1000);
                }
                if (opener.globalList.stopsMarkers.length > 0) {
                    if (opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                        opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = "No definida, continúa hasta el siguiente día.";//opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                    }
                }
                drawDrivingRouteFinish();
            }


        }

        function drawDrivingRouteFinish() {
            clearInterval(opener.globalRoutes.refreshIntervalId);
            getBtnLoadRoute().value = "Cargar Ruta";
            getBtnLoadRoute().disabled = false;
            getBtnPlayPause().set_enabled(true);

            slider = getSliderRouter();
            slider.set_maximumValue(opener.globalClientsRouteHistory.trackDataByImei.length - 1);

            opener.globalRoutes.currentSlideRouteNumber = 0;

            if (opener.globalClientsRouteHistory.trackDataByImei.length > 0) {
                var imei = opener.globalGPSImei.imeiSelected//getImeiValueTreeVehicleSelected();
                var index = Routes.getIndexImei(opener.globalMasterPage.trackDataLastLocationList, imei);
                if (index != -1) {
                    opener.objMapControl.setIconMarker(opener.objMapControl.GPSImeiRoute, opener.globalMasterPage.trackDataLastLocationList[index].image);
                }

                updateCurrentPositionRouteHistory(opener.globalRoutes.currentSlideRouteNumber);

                slider.set_value(0);

                getlbKmFinal().innerHTML = formatTwoDecimals(opener.globalClientsRouteHistory.trackDataByImei[opener.globalClientsRouteHistory.trackDataByImei.length - 1].currentKm) + " kms";
                Routes.enableDisableSliderRoute(true, getSliderRouter());
            }
            else {
                Routes.enableDisableSliderRoute(false, getSliderRouter());
            }
        }

        function ckbSiNoCenterRouteChecked() {
            opener.globalRoutes.isCenterRoute = getCkbSiNoCenterRoute().checked;
        }

        function ckbSiNoCenterGPSImeiChecked() {
            opener.globalRoutes.isCenterGPSImei = getCkbSiNoCenterGPSImei().checked;
        }

        function updateSlideVisibleSpeed(sender, args) {

            var slideValue = sender.get_value();
            opener.globalClientsRouteHistory.speedRouteHistory = 1100 - (slideValue * 100);

            if (opener.globalClientsRouteHistory.slideInterval != null) {
                window.clearInterval(opener.globalClientsRouteHistory.slideInterval);
                opener.globalClientsRouteHistory.slideInterval = null;
                opener.globalClientsRouteHistory.slideInterval = window.setInterval('selectNextSlideRoute()', opener.globalClientsRouteHistory.speedRouteHistory);
            }
        }

        function selectNextSlideRoute() {

            var slider = getSliderRouter();

            if (opener.globalClientsRouteHistory.currentSlideRouteNumber < opener.globalClientsRouteHistory.trackDataByImei.length) {
                updateCurrentPositionRouteHistory(opener.globalClientsRouteHistory.currentSlideRouteNumber);
            }

            var slideNumber = opener.globalClientsRouteHistory.currentSlideRouteNumber + 1;
            if (slideNumber >= opener.globalClientsRouteHistory.trackDataByImei.length) {
                //getBtnPlayPause().checked = !getBtnPlayPause().checked;
                getBtnPlayPause().set_selectedToggleStateIndex(1);
                getBtnPlayPause().set_checked(false);
                stopSlideMovement();
            }
            else {
                slider.set_value(slideNumber);
            }
        }

        function updateCurrentPositionRouteHistory(slideNumber) {
            opener.objMapControl.setPositionMarker(opener.globalClientsRouteHistory.GPSImeiRoute, opener.globalClientsRouteHistory.trackDataByImei[slideNumber].position);
            getlbKmActual().innerText = opener.globalClientsRouteHistory.trackDataByImei[slideNumber].totalKm + " / " + opener.globalClientsRouteHistory.trackDataByImei[opener.globalClientsRouteHistory.trackDataByImei.length - 1].totalKm + " kms";
            getlbKmTime().innerText = opener.globalClientsRouteHistory.trackDataByImei[slideNumber].hour;
            //opener.objMapControl.getDirectionFromPosition(opener.globalClientsRouteHistory.trackDataByImei[slideNumber].position);
            //getlbDirection().innerText = opener.globalClientsRouteHistory.trackDataByImei[slideNumber].direction;
            opener.objMapControl.getDirectionFromPositionBusHistory(opener.globalClientsRouteHistory.trackDataByImei[slideNumber].position, opener.globalClientsRouteHistory);
            //getlbDirection().innerText = opener.globalRoutes.direction;
            getlbDirection().innerText = opener.globalClientsRouteHistory.direction;
            //getlbTrack().innerText = "Vueltas " + opener.globalClientsRouteHistory.trackDataByImei[slideNumber].totalTrack + " / " + opener.globalClientsRouteHistory.totalTrack;
            centerMapChecked(opener.globalClientsRouteHistory.trackDataByImei[slideNumber].position);
            //getlbPeopleIn().innerText = "Personas que Entran " + opener.globalClientsRouteHistory.trackDataByImei[slideNumber].peopleTotalIn + " / " + opener.globalClientsRouteHistory.peopleTotalIn;
            //getlbPeopleOut().innerText = "Personas que Salen " + opener.globalClientsRouteHistory.trackDataByImei[slideNumber].peopleTotalOut + " / " + opener.globalClientsRouteHistory.peopleTotalOut;
        }

        function centerMapChecked(location) {
            if (opener.globalRoutes.isCenterGPSImei) {
                opener.objMapControl.centerMap(location);
            }
        }

        function updateSlideVisibleRoute(sender, args) {

            var slider = sender;

            updateSliderRoute(slider.get_value());

            if (opener.globalClientsRouteHistory.currentSlideRouteNumber < opener.globalClientsRouteHistory.trackDataByImei.length) {
                updateCurrentPositionRouteHistory(opener.globalClientsRouteHistory.currentSlideRouteNumber);
            }
        }

        function updateSliderRoute(slideNumber) {
            opener.globalClientsRouteHistory.currentSlideRouteNumber = slideNumber;
        }

        function showHideHistoryRoute() {
            var ckbSiNoShowRoute = getCkbSiNoShowRoute();
            if (ckbSiNoShowRoute.checked) {
                //Routes.showHistoryRoute(opener);
                //opener.objMapControl.showClientsDirectionDisplay(opener.globalClientsRouteHistory);
            }
            else {
                //Routes.hideHistoryRoute(opener);
            }
        }

        function showOrhideStopsMarkers() {
            if (getCkbSiNoShowStops().checked) {
                Routes.showStopsMarkers(opener);
            }
            else {
                Routes.hideStopsMarkers(opener);
            }
        }

        function playStopSlideMovement(sender, args) {
            if (getBtnPlayPause().get_checked()) {
                playSlideMovement();
            }
            else {
                stopSlideMovement();
            }
            /*if (!args.get_checked()) {
                playSlideMovement();
            }
            else {
                stopSlideMovement();
            }*/
        }

        function playSlideMovement() {
            opener.globalClientsRouteHistory.slideInterval = window.setInterval('selectNextSlideRoute()', opener.globalClientsRouteHistory.speedRouteHistory);
        }

        function stopSlideMovement() {
            if (!opener.globalClientsRouteHistory.slideInterval) return;
            window.clearInterval(opener.globalClientsRouteHistory.slideInterval);
            opener.globalClientsRouteHistory.slideInterval = null;
        }

        function getlbDirection() {
            return $get('<%= lbDirection.ClientID %>');//.innerText;
            }

            function getlbPeopleIn() {
                
            }

            function getlbPeopleOut() {
                
            }

            function getCkbSiNoCenterGPSImei() {
                return $get('<%= ckbSiNoCenterGPSImei.ClientID %>');
            }

            function getrpvRoutesUpdateControl() {
                return "<%= rpvRoutes.ClientID %>";
            }

            function getBtnLoadRoute() {
                return $get('btnCargarRuta');
            }

            function getBtnPlayPause() {
                return $find('<%= btnPlayPause.ClientID %>');
            }

            function getSliderRouter() {
                return $find('<%= RadSliderRoute.ClientID %>');
            }

            function requestStart(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").show(object);
                }
                catch (e) {
                    null;
                }
            }

            function responseEnd(object) {
                //hide the loading panel and clean up the global variables 
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").hide(object);
                }
                catch (e) {
                    null;
                }
            }

            function getCkbSiNoShowRoute() {
                //return $get('<%= ckbSiNoShowRoute.ClientID %>');
            }

            function getlbKmActual() {
                return $get('<%= lbKmActual.ClientID %>');//.innerText;
            }

            function getlbKmTime() {
                return $get('<%= lbTime.ClientID %>');//.innerText;
            }

            function getlbTrack() {
                
            }

            //Utilizada
            function getckbZoomClients() {
                return $get('<%= ckbZoomClients.ClientID %>');
            }
            //Utilizada
            function getckbCenterClients() {
                return $get('<%= ckbCenterClients.ClientID %>');
            }

            function resizeWindow(tab) {

                var index = opener.getIndexPage("ClientsRouteHistory.aspx");

                if (tab == "Reproductor") {
                    opener.openPages[index].oWnd.set_width("1020px");
                    opener.openPages[index].oWnd.set_height("260px");
                }
                else {
                    opener.openPages[index].oWnd.set_width("1250px");
                    opener.openPages[index].oWnd.set_height("370px");
                }
            }

            function OnClientTabSelected(sender, eventArgs) {
                if (eventArgs != null) {
                    var tab = eventArgs.get_tab();
                    resizeWindow(tab.get_text());
                }
            }

        </script>
    </telerik:RadScriptBlock>
</head>
<body onload="getCompaniesByAdminUsername()">
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="AjaxControlID1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="Loading" LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>


        <telerik:RadTabStrip ID="rtsRoutes" runat="server" SelectedIndex="0" MultiPageID="rmpRoutes" OnClientTabSelected="OnClientTabSelected">
            <Tabs>
                <telerik:RadTab runat="server" Text="Rutas" PageViewID="rpvRoutes">
                </telerik:RadTab>
                <telerik:RadTab runat="server" Text="Reproductor" PageViewID="rpvPlayer">
                </telerik:RadTab>
            </Tabs>

        </telerik:RadTabStrip>

        <telerik:RadMultiPage ID="rmpRoutes" runat="server" SelectedIndex="0">
            <telerik:RadPageView ID="rpvRoutes" runat="server">
                <table>
                    <tr>
                        <td>


                            <fieldset>
                                <legend>Fecha Consulta</legend>
                                <telerik:RadCalendar ID="RadCalendar1" runat="server" CultureInfo="es-CR" EnableMultiSelect="false">
                                    <ClientEvents OnDateSelected="getClientsProcessByDateByCompanyID" />

                                </telerik:RadCalendar>
                                <asp:CheckBox ID="ckbZoomClients" runat="server" Text="Acercar Cliente" Width="150px" />
                                <asp:CheckBox ID="ckbCenterClients" runat="server" Text="Centrar Cliente" Width="150px" />
                            </fieldset>



                        </td>
                        <td>
                            <fieldset>
                                <legend>Compañias Registradas</legend>
                                <telerik:RadGrid ID="rgCompaniesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgCompaniesGrid_NeedDataSource" Width="900px">
                                    <ClientSettings>
                                        <Selecting AllowRowSelect="True" />
                                        <ClientEvents OnRowClick="CompaniesGrid_OnRowClick" />
                                        <Scrolling AllowScroll="True" UseStaticHeaders="true" />
                                    </ClientSettings>
                                    <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="CompanyID" NoMasterRecordsText="No hay compañias registradas">
                                        <CommandItemSettings ExportToPdfText="Export to PDF" />
                                        <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
                                        </RowIndicatorColumn>
                                        <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
                                        </ExpandCollapseColumn>
                                        <Columns>
                                            <telerik:GridBoundColumn DataField="CompanyID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="CompanyID" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
                                            </telerik:GridBoundColumn>
                                        </Columns>
                                        <EditFormSettings>
                                            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                                            </EditColumn>
                                        </EditFormSettings>
                                    </MasterTableView>
                                    <FilterMenu EnableImageSprites="true">
                                    </FilterMenu>
                                </telerik:RadGrid>
                            </fieldset>

                            <fieldset>
                                <legend>Información Registrada</legend>
                                <telerik:RadGrid ID="ClientsProcessGrid" runat="server" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" Width="900px" OnNeedDataSource="ClientsProcessGrid_NeedDataSource">
                                    <ClientSettings>
                                        <Selecting AllowRowSelect="True" />
                                        <ClientEvents OnRowClick="ClientsProcessGrid_OnRowClick" />
                                        <Scrolling AllowScroll="True" UseStaticHeaders="true" />
                                    </ClientSettings>
                                    <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" NoMasterRecordsText="No hay registros encontrados" ClientDataKeyNames="Username, GPSImei, Date, LatOrigin, LngOrigin">
                                        <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>

                                        <RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
                                            <HeaderStyle Width="20px"></HeaderStyle>
                                        </RowIndicatorColumn>

                                        <ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
                                            <HeaderStyle Width="20px"></HeaderStyle>
                                        </ExpandCollapseColumn>

                                        <Columns>
                                            <telerik:GridBoundColumn DataField="Username"  HeaderText="Usuario" UniqueName="Usuario" ItemStyle-Width="70px" HeaderStyle-Width="70px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="Name"  HeaderText="Nombre" UniqueName="Nombre" ItemStyle-Width="100px" HeaderStyle-Width="100px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="GPSImei" FilterControlAltText="Filter LastName column" HeaderText="GPSImei" UniqueName="GPSImei" ItemStyle-Width="150px" HeaderStyle-Width="150px">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="GPSName" FilterControlAltText="Filter LastName column" HeaderText="Nombre" UniqueName="GPSName" ItemStyle-Width="130px" HeaderStyle-Width="130px">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="ClientGroupID"  HeaderText="Grupo Cliente ID" UniqueName="ClientGroupID" ItemStyle-Width="70px" HeaderStyle-Width="70px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="ClientGroupName"  HeaderText="Nombre Grupo" UniqueName="ClientGroupName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="Date" FilterControlAltText="Filter LastName column" HeaderText="Fecha" UniqueName="Date" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="TimeBegin" FilterControlAltText="Filter LastName column" HeaderText="Hora Desde" UniqueName="TimeBegin" ItemStyle-Width="80px" HeaderStyle-Width="80px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="TimeEnd" FilterControlAltText="Filter LastName column" HeaderText="Hora Hasta" UniqueName="TimeEnd" ItemStyle-Width="80px" HeaderStyle-Width="80px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="Status" FilterControlAltText="Filter LastName column" HeaderText="Estatus" UniqueName="Status" ItemStyle-Width="100px" HeaderStyle-Width="100px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="Process" FilterControlAltText="Filter LastName column" HeaderText="% Proceso" UniqueName="Process" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="LastExecution" FilterControlAltText="Filter LastName column" HeaderText="Última Actualización" UniqueName="LastExecution" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="LatOrigin"  UniqueName="LatOrigin" ItemStyle-Width="70px" HeaderStyle-Width="70px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" Display="false">
                                            </telerik:GridBoundColumn>
                                            <telerik:GridBoundColumn DataField="LngOrigin"  UniqueName="LngOrigin" ItemStyle-Width="70px" HeaderStyle-Width="70px" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" Display="false">
                                            </telerik:GridBoundColumn>
                                        </Columns>

                                        <EditFormSettings>
                                            <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
                                        </EditFormSettings>

                                        <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                                    </MasterTableView>

                                    <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>

                                    <FilterMenu EnableImageSprites="False"></FilterMenu>
                                </telerik:RadGrid>
                            </fieldset>
                        </td>
                    </tr>
                </table>

            </telerik:RadPageView>
            <telerik:RadPageView ID="rpvPlayer" runat="server">
                <table class="auto-style2">
                    <tr>
                        <td>
                            <table>
                                <tr>
                                    <td>
                                        <fieldset>
                                            <legend>Configuración</legend>
                                            <div style="height: 50px; width: 171px;">

                                                <asp:CheckBox ID="ckbSiNoCenterGPSImei" runat="server" Text="Centrar dispositivo" Checked="true" onclick="javascript:ckbSiNoCenterGPSImeiChecked()" />
                                                <br />
                                                <asp:CheckBox ID="ckbSiNoShowRoute" runat="server" onclick="javascript:showHideHistoryRoute()" Text="Mostrar ruta" Checked="true" Visible="false" />
                                   
                                            </div>
										</fieldset>

                                    </td>
                        
                                </tr>
                                <tr>
                                    <td>
                                        <div style="width: 171px;"></div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <fieldset>
                                            <legend>Velocidad</legend>
                                            <telerik:RadSlider ID="RadSliderSpeed" runat="server" Height="20px" ItemType="None" MaximumValue="11" MinimumValue="1" OnClientLoad="updateSlideVisibleSpeed" OnClientValueChanged="updateSlideVisibleSpeed" TrackPosition="Center" Value="1" Width="150px">
                                            </telerik:RadSlider>
                                        </fieldset>
                                    </td>
                                </tr>
                            </table>

                        </td>
						<td>
                            <fieldset>
                                <legend>Paso 2. Reproducir ruta</legend>
                                <table class="auto-style2" style="text-align: center; vertical-align: top;">
                                    <tr>

                                        <td>
                                            <asp:Label ID="lbKmActual" runat="server" Style="text-align: center" Text="0.0 Km" Width="120px"></asp:Label>
                                        </td>
                                        <td colspan="3">
                                            <telerik:RadSlider ID="RadSliderRoute" runat="server" Height="40px" ItemType="Tick" MaximumValue="120" OnClientLoad="updateSlideVisibleRoute" OnClientValueChanged="updateSlideVisibleRoute" TrackPosition="Center" Value="0" Width="600px">
                                            </telerik:RadSlider>
                                        </td>

                                    </tr>
                                    <tr>
                                        <td>
                                            <%--<asp:Label ID="lbTrack" runat="server" Style="text-align: center" Text="Vueltas ? / ?" Width="120px"></asp:Label>--%>

                                        </td>
                                        <td colspan="3">
                                            <asp:Label ID="lbDirection" runat="server" Style="text-align: center" Text="Dirección" Width="600px"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label ID="lbTime" runat="server" Style="text-align: center" Text="Fecha" Width="120px"></asp:Label>
                                        </td>
                                        <td>
                                            <%--<asp:Label ID="lbPeopleIn" runat="server" Style="text-align: center" Text="Personas Entran ? / ?" Width="200px"></asp:Label>--%>
                                        </td>
                                        <td>
                                            <telerik:RadButton ID="btnPlayPause" runat="server" ButtonType="ToggleButton" Checked="false" Height="32px" OnClientCheckedChanged="playStopSlideMovement" ToggleType="CheckBox" Width="32px" AutoPostBack="False" Enabled="False">
                                                <ToggleStates>
                                                    <telerik:RadButtonToggleState ImageUrl="../../Template/Icons/32px/Button-Play-icon.png" Text="Play" />
                                                    <telerik:RadButtonToggleState ImageUrl="../../Template/Icons/32px/Button-Pause-icon.png" Selected="true" Text="Pause" />
                                                </ToggleStates>
                                            </telerik:RadButton>
                                        </td>
                                        <td>
                                            <%--<asp:Label ID="lbPeopleOut" runat="server" Style="text-align: center" Text="Personas Salen ? / ?" Width="200px"></asp:Label>--%>
                                        </td>
                                    </tr>
                                </table>

                            </fieldset>

                        </td>
                </tr>
				</table>
            </telerik:RadPageView>
        </telerik:RadMultiPage>

        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"></telerik:RadAjaxLoadingPanel>
    </form>
</body>
</html>
